<?php

namespace App\Models\Shop;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
   protected $guarded = [];

   /**
    * 获取一级分类下的二级分类
    */
   public function children()
   {
      return $this->hasMany(Category::class, 'parent_id', 'id');
   }

   /**
    *  获取上级分类
    */
   public function parent()
   {
      return $this->belongsTo(Category::class, 'parent_id', 'id');
   }

   /**
    * 查出一级分类下对应的二级分类
    */
   static function all_categories($where)
   {
      $categories = Category::with(['children' => function ($query) {
         $query->orderBy('sort_order', 'desc');
         $query->with('products');
      }])
         ->where('parent_id', 0)
         ->where($where)
         ->orderBy('sort_order', 'desc')
         ->get();
      return $categories;
   }

   /**
    * 分类下有很多商品
    */
   public function products()
   {
      return $this->hasMany(Product::class, 'category_id', 'id');
   }

   /***
    * 判断分类下是否有商品
    */
   static function check_products($id)
   {
      $category = self::with('products')->find($id);
      if ($category->products->isEmpty()) {
         return true;
      }
      return false;
   }
}
